/**
 * 
 */
package lt.ruta.ui;

import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

import lt.ruta.AutoStateListener;
import lt.ruta.data.Messages;
import lt.ruta.data.Record;

/**
 * @author Vincentas
 *
 */
public class EnterForm extends Form {

	private TextField amountTextField = null;
	
	private TextField descriptionTextField = null;
	
	private AutoStateListener autoStateListener = null;
	
	private ChoiceGroup choiceGroup = null;
	
	public EnterForm(String title) {
		super(title);	
		
		append(getAmountTextField());
		append(getDescriptionTextField());
		append(getChoiceGroup());
		
		setItemStateListener(getAutoStateListener());		
	}
	
	
	
	/**
	 * @return the choiceGroup
	 */
	public ChoiceGroup getChoiceGroup() {
		if (choiceGroup == null) {
			choiceGroup = new ChoiceGroup(Messages.get("enterForm.choiceGroup.title"), Choice.EXCLUSIVE);
			
			choiceGroup.append(Messages.get("enterForm.choiceGroup.credit"), null);
			choiceGroup.append(Messages.get("enterForm.choiceGroup.debit"), null);
			
			choiceGroup.setSelectedIndex(0, true);
		}

		return choiceGroup;
	}



	/**
	 * @return the autoStateListener
	 */
	public AutoStateListener getAutoStateListener() {
		if (autoStateListener == null) {
			autoStateListener = new AutoStateListener(getDescriptionTextField(), new String[0]);
			
		}

		return autoStateListener;
	}

	/**
	 * @return the amountTextField
	 */
	public TextField getAmountTextField() {
		if (amountTextField == null) {
			amountTextField = new TextField(
					Messages.get("enterForm.amountTextField.label"), 
					"", 100, TextField.DECIMAL);			
		}

		return amountTextField;
	}

	/**
	 * @return the descriptionTextField
	 */
	public TextField getDescriptionTextField() {
		if (descriptionTextField == null) {
			descriptionTextField = new TextField(
					Messages.get("enterForm.descriptionTextField.label"),
					"", 100, TextField.ANY);			
		}

		return descriptionTextField;
	}	
	
	public Record getRecord() {
		if (getAmountTextField().getString().length() == 0) {
			return null;
		}
		
		return new Record(
				getChoiceGroup().getSelectedIndex() == 0 ? "-" + getAmountTextField().getString() : getAmountTextField().getString(),
				getDescriptionTextField().getString(),
				System.currentTimeMillis());
	}

	/**
	 * 
	 */
	public void reset() {
		getAmountTextField().setString("");
		getDescriptionTextField().setString("");
	}
}
